package com.anysoft.utils.login;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtil {

	// public static void main(String[] args) {
	// String urlPath="https://ydxjb.icbccs.com.cn/GYGJ/pictureCheckCode.jpeg";
	// }

	public static String SessionID = "";

	/**
	 * 读取连接中的"Set-Cookie值，可能有1个值可能有2个值，因此返回了map类型"
	 * 
	 * @param url_con
	 * @return
	 */
	private static Map<String, String> readCookies(HttpURLConnection url_con) {
		List<String> cookieList = url_con.getHeaderFields().get("Set-Cookie");
		Map<String, String> result = new ConcurrentHashMap<String, String>();
		if (cookieList != null) {
			for (String cookie : cookieList) {
				int p = cookie.indexOf("=");
				String key = cookie.substring(0, p);
				String value = cookie.substring(p + 1, cookie.indexOf(";"));
				result.put(key, value);
			}
		}
		return result;
	}

	/**
	 * 获取后台的sessionid值，因为后台是java后台，识别的是JSESSIONID这个标识,
	 * 因此只取有JSESSIONID标识的sessionid的值
	 * 
	 * @param urlPath
	 * @return
	 */
	public static String getSessionId(String urlPath) {
		SessionID = "JSESSIONID=";
		if (urlPath == null) {
			return null;
		}
		try {
			URL url = new URL(urlPath);
			HttpURLConnection conn = null;
			conn = (HttpURLConnection) url.openConnection();
			conn.setInstanceFollowRedirects(false);
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(5000);
			if (readCookies(conn) != null) {
				SessionID += readCookies(conn).get("JSESSIONID");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return SessionID;
	}
}
